<?php
namespace app\home\controller;

use think\Controller;

class Common extends Controller
{
    public $appid;                         //第三方平台ID

    public $appsecret;                         //第三方平台ID

    public $component_access_token;           //第三方平台应用token（消息校验Token）

    public $token;        //第三方平台应用token（消息校验Token）

    public $encodingAesKey;     //第三方平台应用Key（消息加解密Key）

    public $ticket;



    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $app = model('WeixinAccount')->where('type','1')->find();
        $this->appid = $app['appid'];
        $this->appsecret = $app['appSecret'];
        $this->component_access_token = $this->updateAccessToken();
        $this->token = $app['token'];
        $this->encodingAesKey = $app['encodingAesKey'];
        $this->ticket = $app['component_verify_ticket'];

    }


    /* 更新component_access_token

* @params string $component_verify_ticket

* */

    private function updateAccessToken()

    {

        $weixin_account = model('weixin_account')->where(['type'=>1])->field('id,appId,appSecret,component_access_token,token_expires,component_verify_ticket')->find();

        if($weixin_account['token_expires'] <= time() ) {

            $apiUrl = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';

            $data = '{"component_appid":"'.$weixin_account['appId'].'" ,"component_appsecret": "'.$weixin_account['appSecret'].'","component_verify_ticket": "'.$weixin_account['component_verify_ticket'].'"}';

            $json = json_decode(https_post($apiUrl,$data));

            if(isset($json->component_access_token)) {

                model('weixin_account')->where(['id'=>$weixin_account['id']])->update(['component_access_token'=>$json->component_access_token,'token_expires'=>time()+7200]);

                return $json->component_access_token;
            }
        }
        return $weixin_account['component_access_token'];

    }

    //token 生成
    public function makeToken()
    {

        $str = md5(uniqid(md5(microtime(true)), true)); //生成一个不会重复的字符串
        $str = sha1($str); //加密
        dump(base64_encode('2s3d6g4h7xogh96785sgxheowpzlg529'));
        echo '<br>';
        echo base64_decode('MnMzZDZnNGg3eG9naDk2Nzg1c2d4aGVvd3B6bGc1Mjk=');
//        return $str;
    }

    public function logResult($path,$data){
        file_put_contents($path, '['.date('Y-m-d : h:i:sa',time()).']'.$data."\r\n",FILE_APPEND);
    }
}